from django.contrib import admin
from django.db import models as m
import datetime as dt
from bddjango.adminclass import ListDisplayAdmin
from . import models
from .utils import get_statistics_result


# --- 访问记录表
@admin.register(models.Statistics)
class Statics(ListDisplayAdmin):
    list_per_page = 30
    search_fields = ['ip']
    list_filter = ['access_date', 'mobile', 'ip', ]
    readonly_fields = ['access_date', 'access_time']


# --- 流量统计图 ---


@admin.register(models.ViewsByDayModel)
class ViewsByDayAdmin(ListDisplayAdmin):
    list_filter = (
        'access_date',      # 图表过滤字段
    )
    change_list_template = 'admin/admin_test.html'
    default_days = 0        # 启用默认分析天数

    def changelist_view(self, request, extra_context=None):
        response = super().changelist_view(
            request,
            extra_context=extra_context
        )

        try:
            qs: m.QuerySet = response.context_data['cl'].queryset.order_by()
        except (AttributeError, KeyError):
            return response

        if self.default_days and qs.count() == models.Statistics.objects.count():
            days = self.default_days
            print(f'--- 默认查最近{days}天!')
            end_t = dt.datetime.now()
            start_t = end_t - dt.timedelta(days=days)
            qs = models.Statistics.objects.filter(access_date__range=[start_t, end_t]).order_by()

        data = get_statistics_result(qs)
        response.context_data['date'] = data
        return response

